/***********************************************************************
 *            Project: CoreCms
 *        ProjectName: 核心内容管理系统                                
 *                Web: https://www.corecms.net                      
 *             Author: 大灰灰                                          
 *              Email: jianweie@163.com                                
 *         CreateTime: 2023-04-07 10:19:24
 *        Description: 暂无
 ***********************************************************************/

using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using CoreCms.Net.Caching.Manual;
using CoreCms.Net.Configuration;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.ViewModels.Basics;
using CoreCms.Net.IRepository;
using CoreCms.Net.IRepository.UnitOfWork;
using CoreCms.Net.Model.ViewModels.UI;
using SqlSugar;
using static SKIT.FlurlHttpClient.Wechat.Api.Models.ChannelsECOrderGetResponse.Types.Order.Types;
using static SKIT.FlurlHttpClient.Wechat.Api.Models.CgibinExpressDeliveryOpenMessageFollowWaybillRequest.Types;
using static NPOI.HSSF.Util.HSSFColor;

namespace CoreCms.Net.Repository
{
    /// <summary>
    ///  接口实现
    /// </summary>
    public class CoreShopOrderMeetingGoodsRepository : BaseRepository<CoreShopOrderMeetingGoods>, ICoreShopOrderMeetingGoodsRepository
    {
        private readonly IUnitOfWork _unitOfWork;
        public CoreShopOrderMeetingGoodsRepository(IUnitOfWork unitOfWork) : base(unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

       #region 实现重写增删改查操作==========================================================

        /// <summary>
        /// 重写异步插入方法
        /// </summary>
        /// <param name="entity">实体数据</param>
        /// <returns></returns>
        public new async Task<AdminUiCallBack> InsertAsync(CoreShopOrderMeetingGoods entity)
        {
            var jm = new AdminUiCallBack();

            var bl = await DbClient.Insertable(entity).ExecuteReturnIdentityAsync() > 0;
            jm.code = bl ? 0 : 1;
            jm.msg = bl ? GlobalConstVars.CreateSuccess : GlobalConstVars.CreateFailure;
            if (bl)
            {
                await UpdateCaChe();
            }

            return jm;
        }

        /// <summary>
        /// 重写异步更新方法
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public new async Task<AdminUiCallBack> UpdateAsync(CoreShopOrderMeetingGoods entity)
        {
            var jm = new AdminUiCallBack();

            var oldModel = await DbClient.Queryable<CoreShopOrderMeetingGoods>().In(entity.id).SingleAsync();
            if (oldModel == null)
            {
            jm.msg = "不存在此信息";
            return jm;
            }
            //事物处理过程开始
        	oldModel.id = entity.id;
            oldModel.meetingid = entity.meetingid;
            oldModel.goodid = entity.goodid;
            oldModel.meetingminimum = entity.meetingminimum;
            oldModel.meetingprice = entity.meetingprice;

            //事物处理过程结束
            var bl = await DbClient.Updateable(oldModel).ExecuteCommandHasChangeAsync();
            jm.code = bl ? 0 : 1;
            jm.msg = bl ? GlobalConstVars.EditSuccess : GlobalConstVars.EditFailure;
            if (bl)
            {
                await UpdateCaChe();
            }

            return jm;
        }

        /// <summary>
        /// 重写异步更新方法
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public new async Task<AdminUiCallBack> UpdateAsync(List<CoreShopOrderMeetingGoods> entity)
        {
            var jm = new AdminUiCallBack();

            var bl = await DbClient.Updateable(entity).ExecuteCommandHasChangeAsync();
            jm.code = bl ? 0 : 1;
            jm.msg = bl ? GlobalConstVars.EditSuccess : GlobalConstVars.EditFailure;
            if (bl)
            {
                await UpdateCaChe();
            }

            return jm;
        }

        /// <summary>
        /// 重写删除指定ID的数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public new async Task<AdminUiCallBack> DeleteByIdAsync(object id)
        {
            var jm = new AdminUiCallBack();

            var bl = await DbClient.Deleteable<CoreShopOrderMeetingGoods>(id).ExecuteCommandHasChangeAsync();
            jm.code = bl ? 0 : 1;
            jm.msg = bl ? GlobalConstVars.DeleteSuccess : GlobalConstVars.DeleteFailure;
            if (bl)
            {
                await UpdateCaChe();
            }

            return jm;
        }

        /// <summary>
        /// 重写删除指定ID集合的数据(批量删除)
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public new async Task<AdminUiCallBack> DeleteByIdsAsync(int[] ids)
        {
            var jm = new AdminUiCallBack();

            var bl = await DbClient.Deleteable<CoreShopOrderMeetingGoods>().In(ids).ExecuteCommandHasChangeAsync();
            jm.code = bl ? 0 : 1;
            jm.msg = bl ? GlobalConstVars.DeleteSuccess : GlobalConstVars.DeleteFailure;
            if (bl)
            {
                await UpdateCaChe();
            }

            return jm;
        }

        #endregion

       #region 获取缓存的所有数据==========================================================

        /// <summary>
        /// 获取缓存的所有数据
        /// </summary>
        /// <returns></returns>
        public async Task<List<CoreShopOrderMeetingGoods>> GetCaChe()
        {
            var cache = ManualDataCache.Instance.Get<List<CoreShopOrderMeetingGoods>>(GlobalConstVars.CacheCoreShopOrderMeetingGoods);
            if (cache != null)
            {
                return cache;
            }
            return await UpdateCaChe();
        }

        /// <summary>
        ///     更新cache
        /// </summary>
        public async Task<List<CoreShopOrderMeetingGoods>> UpdateCaChe()
        {
            var list = await DbClient.Queryable<CoreShopOrderMeetingGoods>().With(SqlWith.NoLock).ToListAsync();
            ManualDataCache.Instance.Set(GlobalConstVars.CacheCoreShopOrderMeetingGoods, list);
            return list;
        }

        #endregion


        #region 重写根据条件查询分页数据
        /// <summary>
        ///     重写根据条件查询分页数据
        /// </summary>
        /// <param name="predicate">判断集合</param>
        /// <param name="orderByType">排序方式</param>
        /// <param name="pageIndex">当前页面索引</param>
        /// <param name="pageSize">分布大小</param>
        /// <param name="orderByExpression"></param>
        /// <param name="blUseNoLock">是否使用WITH(NOLOCK)</param>
        /// <returns></returns>
        public new async Task<IPageList<CoreShopOrderMeetingGoods>> QueryPageAsync(Expression<Func<CoreShopOrderMeetingGoods, bool>> predicate,
            Expression<Func<CoreShopOrderMeetingGoods, object>> orderByExpression, OrderByType orderByType, int pageIndex = 1,
            int pageSize = 20, bool blUseNoLock = false)
        {
            RefAsync<int> totalCount = 0;
            List<CoreShopOrderMeetingGoods> page;
            if (blUseNoLock)
            {
                page = await DbClient.Queryable<CoreShopOrderMeetingGoods>()
                .OrderByIF(orderByExpression != null, orderByExpression, orderByType)
                .WhereIF(predicate != null, predicate)
                 .LeftJoin<CoreCmsGoods>((o, good) => o.goodid == good.id)
                  .LeftJoin<CoreCmsProducts>((o, good, pd) => o.goodid == pd.goodsId && pd.isDefalut == true && pd.isDel == false)
                .Select((o, good, pd) => new CoreShopOrderMeetingGoods
                {
                      id = o.id,
                  meetingid = o.meetingid,
                  goodid = o.goodid,

                    meetingminimum = o.meetingminimum,
                meetingprice = o.meetingprice,
                goods = new CoreCmsGoods
                    {

                        id = good.id,
                        bn = good.bn,
                        name = good.name,
                        brief = good.brief,
                        image = good.image,
                        images = good.images,
                        video = good.video,
                        productsDistributionType = good.productsDistributionType,
                        goodsCategoryId = good.goodsCategoryId,
                        goodsTypeId = good.goodsTypeId,
                        brandId = good.brandId,
                        isNomalVirtual = good.isNomalVirtual,
                        isMarketable = good.isMarketable,
                        unit = good.unit,
                        //intro = good.intro,
                        spesDesc = good.spesDesc,
                        parameters = good.parameters,
                        commentsCount = good.commentsCount,
                        viewCount = good.viewCount,
                        buyCount = good.buyCount,
                        uptime = good.uptime,
                        downtime = good.downtime,
                        sort = good.sort,
                        labelIds = good.labelIds,
                        newSpec = good.newSpec,
                        openSpec = good.openSpec,
                        createTime = good.createTime,
                        updateTime = good.updateTime,
                        isRecommend = good.isRecommend,
                        isHot = good.isHot,
                        isDel = good.isDel,
                        sn = pd.sn,
                        price = pd.price,
                        costprice = pd.costprice,
                        mktprice = pd.mktprice,
                        stock = pd.stock,
                        freezeStock = pd.freezeStock,
                        weight = pd.weight
                    }
                     
                   

                }).With(SqlWith.NoLock).ToPageListAsync(pageIndex, pageSize, totalCount);
            }
            else
            {
                page = await DbClient.Queryable<CoreShopOrderMeetingGoods>()
                    
                .OrderByIF(orderByExpression != null, orderByExpression, orderByType)
                  .WhereIF(predicate != null, predicate)
                 .LeftJoin<CoreCmsGoods>((o, good) => o.goodid == good.id)
                  .LeftJoin<CoreCmsProducts>((o, good, pd) => o.goodid == pd.goodsId && pd.isDefalut == true && pd.isDel == false)
                     .Select((o, good, pd) => new CoreShopOrderMeetingGoods
                     {
                    id = o.id,
                    meetingid = o.meetingid,
                    goodid = o.goodid,

                         meetingminimum = o.meetingminimum,
                         meetingprice = o.meetingprice,
                         goods = new CoreCmsGoods
                    {
                        id = good.id,
                        bn = good.bn,
                        name = good.name,
                        brief = good.brief,
                        image = good.image,
                        images = good.images,
                        video = good.video,
                        productsDistributionType = good.productsDistributionType,
                        goodsCategoryId = good.goodsCategoryId,
                        goodsTypeId = good.goodsTypeId,
                        brandId = good.brandId,
                        isNomalVirtual = good.isNomalVirtual,
                        isMarketable = good.isMarketable,
                        unit = good.unit,
                        //intro = good.intro,
                        spesDesc = good.spesDesc,
                        parameters = good.parameters,
                        commentsCount = good.commentsCount,
                        viewCount = good.viewCount,
                        buyCount = good.buyCount,
                        uptime = good.uptime,
                        downtime = good.downtime,
                        sort = good.sort,
                        labelIds = good.labelIds,
                        newSpec = good.newSpec,
                        openSpec = good.openSpec,
                        createTime = good.createTime,
                        updateTime = good.updateTime,
                        isRecommend = good.isRecommend,
                        isHot = good.isHot,
                        isDel = good.isDel,
                        sn = pd.sn,
                        price = pd.price,
                        costprice = pd.costprice,
                        mktprice = pd.mktprice,
                        stock = pd.stock,
                        freezeStock = pd.freezeStock,
                        weight = pd.weight
                    }

                }).ToPageListAsync(pageIndex, pageSize, totalCount);
            }
            var list = new PageList<CoreShopOrderMeetingGoods>(page, pageIndex, pageSize, totalCount);
            return list;
        }

        #endregion

    }
}
